import { RequiredValidateError, RuleValidateError, ValidateErrorInfo } from '@/ts/base/model';
import WorkFormService from '@/ts/scripting/core/services/WorkFormService';
import { Tag, message } from 'antd';
import React, { ReactNode, useEffect, useState } from 'react';
import { ValidateMessagePanel } from '../../../../Common/Validate/ValidateMessagePanel';
import { is } from '@/ts/base/common/lang/type';

interface IProps {
  service: WorkFormService;
  onErrorClick?: (error: ValidateErrorInfo) => void;
}

const FormValidateMessage: React.FC<IProps> = (props) => {
  const [validateVisible, setValidateVisible] = useState(false);
  const [validateErrors, setValidateErrors] = useState<ValidateErrorInfo[]>([]);

  useEffect(() => {
    const dispose = props.service.onScoped('afterValidate', (args) => {
      setValidateErrors([...args]);
      if (args.length > 0) {
        setValidateVisible(true);
      } else {
        setValidateVisible(false);
      }
    });
    return () => {
      dispose();
    };
  }, []);

  function renderPosition(error: ValidateErrorInfo) {
    let ret: ReactNode = error.position;

    let formId = (error as any).formId;
    let formName = formId ? (
      <Tag color="processing" style={{ marginLeft: '8px' }}>
        {props.service.formInfo[formId]?.form.name ?? formId}
      </Tag>
    ) : <></>;

    if (is<RequiredValidateError>(error, (error as any).field)) {
      return (
        <>
          <span>{error.field.name}</span>
          {formName}
        </>
      );
    } else if (is<RuleValidateError>(error, (error as any).rule)) {
      return (
        <>
          <span>规则：{error.rule.name}</span>
          {formName}
        </>
      );
    }
    return ret;
  }

  return (
    <ValidateMessagePanel
      validateErrors={validateErrors}
      visible={validateVisible}
      onVisibleChange={setValidateVisible}
      onErrorClick={props.onErrorClick}
      renderPosition={renderPosition}
    />
  );
};

export default FormValidateMessage;
